import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/empty_widget.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/model/coupon_item.dart';
import 'coupon_list_item_widget.dart';
import 'package:gzmall_app/common/color_common.dart';

class CouponListWidget extends StatefulWidget {
  int id;

  CouponListWidget(this.id);

  @override
  State<StatefulWidget> createState() => CouponListWidgetState(this.id);
}

class CouponListWidgetState extends State<CouponListWidget> {
  List<CouponItem> _coupons = [];
  int id;

  double _itemWidth;
  bool _isShowWait = false;
  int _curPId = 0;

  int _curPage = 1;
  RefreshListView _refreshListView;
  String _emptyTips = '正在加载数据中...';
  bool _showEmpty = false;

  CouponListWidgetState(this.id);

  void init() {
    var size = MediaQuery.of(context).size;
    _itemWidth = (size.width - 15) / 2;
  }

  @override
  void initState() {
    super.initState();
    _getCoupons(id, 1);
  }

  @override
  Widget build(BuildContext context) {
    init();
    return Stack(
      children: <Widget>[
        _buildGirdList(),
        _isShowWait != null && _isShowWait
            ? Center(child: _getWaitingDialog())
            : Container(),
      ],
    );
  }

  Widget _buildGirdList() {
    List<Widget> couponList = _coupons
        .map((item) => CouponListItemWidget(item, _itemWidth, () {
              _click(item);
            }, () {
              _click(item);
            }))
        .toList();
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: GridView.count(
        shrinkWrap: true,
        padding: const EdgeInsets.only(left: 5.0, right: 5.0, top: 5.0),
        crossAxisSpacing: 5.0,
        mainAxisSpacing: 5.0,
        controller: new ScrollController(keepScrollOffset: false),
        crossAxisCount: 2,
        childAspectRatio: _itemWidth / (_itemWidth + _itemWidth / 1.8),
        children: couponList,
      ),
      emptyTips: _emptyTips,
      showEmpty: _showEmpty,
      onReload: () {
        _getCoupons(id, 1);
      },
    );
    return Container(
        color: Colors.white,
        width: double.infinity,
        height: double.infinity,
        child: _refreshListView);
  }

  _getWaitingDialog() {
    return Container(
      width: 200.0,
      height: 150.0,
      decoration: BoxDecoration(
          color: ColorCommon.translucent2,
          borderRadius: BorderRadius.all(Radius.circular(10.0))),
      padding: const EdgeInsets.all(20.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SpinKitFadingCircle(
            color: Colors.white,
          ),
          Padding(
            padding: const EdgeInsets.only(top: 10.0),
            child: Text(
              "领取成功\n正在跳转商品详情...",
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  _showWait() {
    setState(() {
      _isShowWait = true;
    });
    new Future.delayed(const Duration(milliseconds: 0)).then((val) {
      setState(() {
        _isShowWait = false;
        if (_curPId != null && _curPId > 0) {
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new GoodsDetailsPage(productId: _curPId);
          }));
        } else {
          ToastUtil.showMessageToast("优惠券数据有误，请重试");
        }
      });
    });
  }

  void _onRefresh(bool up) {
    if (up) {
      _getCoupons(id, 1);
    } else {
      _getCoupons(id, _curPage + 1);
    }
  }

  _getCoupons(int shopCategoryId, int page) {
    bool isGetNew = page == 1;
    Map<String, String> params = {
      "page": page.toString(),
      "shop_category_id": shopCategoryId.toString(),
    };
    NetUtil.get(
        context,
        Api.coupons,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : CouponItem.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            _emptyTips = '没有符合条件的优惠券';
            if (isGetNew) {
              _coupons = _dataList;
            } else {
              _coupons.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty = isGetNew && (_coupons == null || _coupons.length <= 0);
            _emptyTips = '没有符合条件的优惠券';
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }

  _click(CouponItem item) {
    if (_isShowWait) {
      return;
    }
    _curPId = item?.spu?.id;
    if (item.had != null && item.had) {
      _showWait();
      return;
    }
    if (item?.coupon?.id != null) {
      _receiveCoupon(item.coupon.id);
    }
  }

  _receiveCoupon(int cId) {
    Map<String, String> params = {
      "coupon_id": cId.toString(),
    };

    NetUtil.post(context, Api.userCoupons, (data, message) {
      _getCoupons(this.id, 1);
      _showWait();
    }, params: params, isShowLoading: true);
  }
}
